package com.example.jqying.androiddemo.recyclerView.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.jqying.androiddemo.R;

import java.util.List;

/**
 * Created by apple on 2018/6/23.
 */

public class LinearAdapter extends RecyclerView.Adapter<LinearAdapter.LinearViewHolder> {


    private Context mContext;
    private List<String > mList;
    private OnitemClickListener mlistener;


    /*
    *   上接LinearRecycleActivity
    *   使用流程
    *   1。构造时传入Context上下文
    *   2。设置RecycleView中item的数量
    *   3。设置每个Item的layout，通过LinearViewHolder
    *   4。linearViewHolder中的layout绑定到RecycleView中
    *   5。通过onBindView设置layout内部控件的属性
     */

    public LinearAdapter(Context context,OnitemClickListener listener){
        mContext = context;
        this.mlistener = listener;

    }

    @Override
    public LinearViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new LinearViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_linear_item,parent,false ));
    }

    @Override
    public void onBindViewHolder(LinearViewHolder holder, final int position) {

        if(holder.textView!=null) {
            holder.textView.setText("hello world again!!!");

        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //position 为触发事件的Item的编号
                //Toast.makeText(mContext,"Clicked : "+ position,Toast.LENGTH_SHORT).show();

                //调用用户定义的事件处理函数，类似C#的订阅和发布关系
                mlistener.onClick(position);
            }
        });

        //也可以处理其它事件，也可运用低耦合的接口
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                return false;
            }
        });


    }

    @Override
    public int getItemCount() {
        return 30;
    }


    class LinearViewHolder extends RecyclerView.ViewHolder{

        private TextView textView;

        public LinearViewHolder(View itemView) {
            super(itemView);
            textView = (TextView)itemView.findViewById(R.id.tv_title);
        }
    }


    /*
    *   定义一个interface用于传入用户定义的事件
     */

    public interface OnitemClickListener{
        void onClick(int pos);
    }
}
